<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="表名">
              <j-input placeholder="请输入表名" v-model="queryParam.tableName"></j-input>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="数据源名称" >
              <a-select :filter-option="filterOption" show-search allowClear v-model="queryParam.dataSource" :getPopupContainer="trigger => trigger.parentNode" placeholder="请选择数据源">
                <a-select-option  :value="item.code" :key="item.code" v-for="item in dataSourceList">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleOperate(1)" type="primary" icon="plus">新增</a-button>
      <a-button @click="importOnlineForm" type="primary" icon="database">导入数据库表</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel(undefined, '移除')"><a-icon type="delete" />移除</a-menu-item>
          <a-menu-item key="2" @click="loadData"><a-icon type="sync" />状态刷新</a-menu-item>
        </a-menu>
        <a-button type="primary" icon="tool">批量操作<a-icon type="down" /></a-button>
      </a-dropdown>
      <j-super-query :fieldList="superQueryFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>
    </div>
    <!-- table区域-begin -->
    <div class="data-sheet-table">
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i>
        已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>
        项
        <a style="margin-left: 24px" @click="onClearSelected">取消勾选</a>
      </div>
      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :scroll="{ x: 1300, y: tableHeight }"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">
        <template slot="customDefaultRender" slot-scope="text">
          <span>{{ text || '-' }}</span>
        </template>
        <!-- 状态渲染模板 -->
        <template slot="customRenderStatus" slot-scope="status">
          <a-tag v-if="status==0" color="red">停用</a-tag>
          <a-tag v-if="status==1" color="green">启用</a-tag>
        </template>
        <template slot="action" slot-scope="text, record">
          <a-button
            type="link"
            @click="handleOperate(2, record)"
          >编辑</a-button>
          <a-divider type="vertical"/>
          <a-dropdown>
            <a class="ant-dropdown-link">更多
              <a-icon type="down"/>
            </a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleOperate(3, record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a @click="handleViewData(record)">查看数据</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定移除吗?" @confirm="() => handleDelete(record.id)" placement="left">
                  <a>移除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </template>
      </a-table>
    </div>
    <!-- table区域-end -->
    <!-- 表单区域 -->
    <onl-cgform-head-modal ref="modalForm" @ok="modalFormOk"></onl-cgform-head-modal>
    <trans-db2-online ref="transd2o" @ok="transOk"></trans-db2-online>
    <code-generator ref="cg"></code-generator>
    <onl-cgform-button-list ref="btnList"></onl-cgform-button-list>
    <onl-enhance-java-list ref="ehjava"></onl-enhance-java-list>
    <onl-enhance-sql-list ref="ehsql"></onl-enhance-sql-list>
    <data-edit ref="dataEdit" @ok="modalFormOk"></data-edit>
  </a-card>
</template>

<script>
import OnlCgformHeadModal from './modules/OnlCgformHeadModal'
import OnlCgformButtonList from './button/OnlCgformButtonList'
import OnlEnhanceJavaList from './enhance/OnlEnhanceJavaList'
import OnlEnhanceSqlList from './enhance/OnlEnhanceSqlList'
import TransDb2Online from './modules/TransDb2Online'
import CodeGenerator from './modules/CodeGenerator'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { postAction, getAction } from '@/api/manage'
import JInput from '@comp/jeecg/JInput'
import DataEdit from '@/views/data-edit/DataEdit'

export default {
  name: 'OnlCgformHeadList',
  components: {
    JInput,
    OnlCgformHeadModal,
    TransDb2Online,
    CodeGenerator,
    OnlCgformButtonList,
    OnlEnhanceJavaList,
    OnlEnhanceSqlList,
    DataEdit
  },
  mixins: [JeecgListMixin],
  data() {
    return {
      description: '数据表管理页面',
      loading: true,
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '数据源名称',
          align: 'center',
          dataIndex: 'dataSource_dictText',
          scopedSlots: { customRender: 'customDefaultRender' }
        },
        {
          title: '表名',
          align: 'center',
          dataIndex: 'tableName'
        },
        {
          title: '表的汉字描述',
          align: 'center',
          dataIndex: 'tableComment',
          scopedSlots: { customRender: 'customDefaultRender' }
        },
        {
          title: '表存储的数据量',
          align: 'center',
          dataIndex: 'dataRows',
          scopedSlots: { customRender: 'customDefaultRender' }
        },
        {
          title: '表数据更新时间',
          align: 'center',
          dataIndex: 'updateTime',
          scopedSlots: { customRender: 'customDefaultRender' }
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'status',
          scopedSlots: { customRender: 'customRenderStatus' },
          filterMultiple: false,
          filters: [
            { text: '启用', value: '1' },
            { text: '停用', value: '0' }
          ]
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 130,
          scopedSlots: { customRender: 'action' }
        }
      ],
      superQueryFlag: false,
      dataSourceList: [],
      superQueryParams: '',
      superQueryFieldList: [
        { type: 'input', value: 'dataSource', text: '数据源名称', dictCode: 'sys_data_source,name,code' },
        { type: 'input', value: 'tableName', text: '表名称' },
        { type: 'input', value: 'tableType', text: '表类型' },
        { type: 'input', value: 'dataRows', text: '表存储的数据量' },
        { type: 'input', value: 'createBy', text: '创建人' }
      ],
      url: {
        list: '/dataSource/scSituationTable/list',
        delete: '/dataSource/scSituationTable/delete',
        deleteBatch: '/dataSource/scSituationTable/deleteBatch'
      },
      tableTypeDictOptions: [],
      sexDictOptions: [],
      syncFormId: '',
      synMethod: 'normal',
      syncLoading: false,
      onlineUrlTitle: '',
      onlineUrlVisible: false,
      onlineUrl: '',
      selectedRowKeys: [],
      selectedRows: [],
      tableHeight: 706
    }
  },
  created() {
    // 初始化字典 - 表类型
    this.$initDictOptions('cgform_table_type').then(res => {
      if (res.success) {
        this.tableTypeDictOptions = res.result
      }
    })
    this.getDataSourceList()
  },
  mounted() {
    // 获取容器当前高度，重设表格的最大高度
    setTimeout(() => {
      this.getTableMaxHeight()
    }, 200)
    window.onresize = () => {
      this.getTableMaxHeight() // 获取容器当前高度，重设表格的最大高度
    }
  },
  methods: {
    handleOperate(index, data) {
      this.$refs.modalForm.operateType = index
      switch (index) {
        case 1:
          this.handleAdd()
          break
        case 2:
          this.handleEdit(data)
          break
        case 3:
          this.handleDetail(data)
          break
      }
    },
    filterOption(input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 获取容器当前高度，重设表格的最大高度
    getTableMaxHeight() {
      this.$nextTick(() => {
        if (document.querySelector('.common-scroll-box') === null) return
        const box = document.querySelector('.common-scroll-box').attributes
        const boxHeight = box[0].ownerElement.clientHeight - 24 - 66 - 50 - 39 - 16 - 56 - 50
        this.tableHeight = boxHeight
      })
    },
    getDataSourceList() {
      getAction('/sys/dataSource/list', { pageNo: 1, pageSize: 10000 }).then((res) => {
        if (res.success) {
          if (res.result.records != null) {
            this.dataSourceList = res.result.records.filter(item => item.dbStatus == '1')
          } else {
            this.dataSourceList = []
          }
        } else {
          this.dataSourceList = []
        }
      })
    },
    doDbSynch(id) {
      postAction(this.url.doDbSynch + id, { synMethod: '1' }).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.loadData()
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    // 导入数据库表
    importOnlineForm() {
      this.$refs.transd2o.show()
    },
    transOk() {
      this.loadData()
    },
    onSelectChange(keys, rows) {
      this.selectedRowKeys = keys
      this.selectedRows = rows
    },
    batchDeleteCust() {
      if (!this.url.deleteBatch) {
        this.$message.error('请设置url.deleteBatch属性!')
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      }
    },
    /**
    * @description 查看数据
    * @param {Object} record
    * @returns void
    */
    handleViewData(record) {
      this.$refs.dataEdit.handleOpenData(record,
        {
          dataSource: record.dataSource,
          serviceCode: record.serviceCode,
          tableName: record.tableName
        }
      )
    }
  }
}
</script>

<style lang="less" scoped>
  @import '~@assets/less/common.less';

  .data-sheet-table {
    .ant-btn-link {
      padding: 0;
      margin-right: 0;
    }
  }

  .ant-table td,th {
    white-space: nowrap;
  }
  .anty-row-operator button {
    margin: 0 5px;
  }
  .ant-btn-danger {
    background-color: #ffffff;
  }
  .valid-error-cust {
    .ant-select-selection {
      border: 2px solid #f5222d;
    }
  }
</style>
